import axios from 'axios'
import storage from '../utils/storage'
// import router from '../router';
import { ElMessageBox } from 'element-plus'


const instance = axios.create({
  // baseURL: 'http://localhost:3000',
  timeout: 5000
})

// 请求拦截器
instance.interceptors.request.use((config: any) => {
  // 请求拦截要处理的内容
  // console.log('config', config)
  const token = storage.get('CURRENT_TOKEN', '')
  // console.log('请求拦截要处理的内容 token CURRENT_TOKEN', token)
  config.headers = {
    Authorization: `Bearer ${token}`
  }
  return config
}, err => {
  console.log('请求失败', err)
})

// 响应拦截器
instance.interceptors.response.use(res => {
  // 响应拦截要处理的内容
  // console.log('响应拦截要处理的内容', res)
  // res.status = 200;

  const { code, msg } = res.data
  if (code == 401) {
    ElMessageBox.alert(msg, '提示', {
      confirmButtonText: '确定',
      callback: () => {
        console.log('go login')
        // router.push({ name: 'Login' })
        window.location.replace('/login')
        // router.push('/login');
        // storage.clear();
      }
    });
  } else if (code == 500) {
    ElMessageBox.alert(msg, '提示', {
      confirmButtonText: '确定',
      callback: () => { }
    });
    return res
  } else if (code !== 200) {
    // alert(message)
    ElMessageBox.alert(msg, '提示', {
      confirmButtonText: '确定',
      callback: () => {
        // window.location.replace('/login')
      }
    });
    return res
  }
  return res
}, err => {

  ElMessageBox.alert('响应失败:' + err.message, '提示', {
    confirmButtonText: '确定',
    callback: () => {
      // storage.clear();
      // router.push({ name: 'Login' })
      window.location.replace('/login')
      // router.push('/login');
    }
  });
  return Promise.reject(err);
})

/**
 * 封装 http 请求的方法
 * @param option 配置对象，属性包括
 * method 请求方法
 * path 请求接口地址
 * params 请求参数
 */
async function http(option: { method: string, path: string, params?: any, data?: any }) {
  // console.log('http', option.params)
  const method = option.method.toLocaleString();
  const requestParams = {
    method,
    url: option.path,
    // params: option.params,
  };
  if (option.params) {
    if (method === 'GET') {
      // console.log('http GET', option.params)
      Object.assign(requestParams, { params: option.params });
    } else {
      Object.assign(requestParams, { data: option.params });
    }
  }
  if (option.data) {
    Object.assign(requestParams, { data: option.data });
  }
  // console.log('requestParams', requestParams)
  try {
    const result = await instance.request(requestParams);
    return result.data;
  } catch (error) {
    // 错误处理逻辑
    throw error;
  }
} 
const method = {
  GET: 'GET',
  POST: 'POST',
  PUT: 'PUT',
  DELETE: 'DELETE',
}
export { method }
export default http
